Skip to content

Extraction - #14

Closed
sickerine wants to merge 424 commits into
mainfrom
new
Closed

sickerine wants to merge 424 commits into
mainfrom
new

Conversation

@sickerine

Copy link
Copy Markdown
Collaborator

No description provided.

Two parallel plans in Wave 1:
- Plan 01: golden set data, eval test runner (vitest-evals + autoevals),
  CI workflow with extraction path filter
- Plan 02: qualityChecks schema, hourly sampling cron, quality trend
  query, review queue, and updateReviewStatus mutation
- Add qualityChecks table to schema with answerId, verdict, judgeModel,
  timestamp, reviewStatus fields and by_answerId/by_timestamp indexes
- Add reviewStatusValidator (pending/reviewed/promoted) to extraction validators
- Add vitest-evals and autoevals as devDependencies
- Create tests/evals/screening-golden.ts with GoldenCase interface
- 20 hand-labeled cases: 7 include, 7 exclude, 6 insufficient_evidence
- Parsing source distribution: 4 pmc, 5 arxiv, 4 unpdf, 4 gemini, 3 abstract_only
- Each case has realistic academic paper body text with validated source spans
- Runtime span validation via makeCase helper at module load time
- Create qualitySampling.ts internalAction that picks a random eligible
  extraction result, re-runs the critic, and writes verdict to qualityChecks
- Create qualitySamplingHelpers.ts with internalQuery/internalMutation
  helpers for DB access from the "use node" action
- Register hourly "quality sampling" cron in crons.ts
- Early-return silently when no eligible results exist (D-14)
- Verdict-based reviewStatus assignment: unsupported -> pending (D-19)
… mutation

- Add getQualityTrend query: 7-day rolling pass-rate from qualityChecks
  with supported/unsupported/partial/total/passRate aggregation
- Add getReviewQueue query: pending items joined with answer/paper context,
  bounded to 100 items, most recent first
- Add updateReviewStatus mutation: allows reviewed/promoted transitions only,
  cannot reset to pending (T-96-05)
- All public surfaces auth-gated (T-96-04, T-96-05)
…rers

- Add screening-eval.test.ts with RUN_EVALS=1 gate via describe.skipIf
- Use describeEval from vitest-evals for per-case scoring
- Factuality scorer (autoevals) compares extracted answers to expected
- Custom citationSubstringMatchScorer uses Levenshtein 85% threshold
- Aggregate threshold assertions: recall-on-include >= 95%, citation-validity >= 98%
- All 42 tests properly skip when RUN_EVALS is not set (zero LLM cost)
- Add .github/workflows/evals.yml triggered on PRs touching extraction code
- Path filter: convex/extraction/**, lib/extraction/**, tests/evals/**, lib/ai/core/prompts.ts
- RUN_EVALS=1 enables the describe.skipIf gate in eval tests
- Routes autoevals Factuality through OpenRouter (OPENAI_BASE_URL)
- 15-minute timeout for 20 LLM calls with retries
- Placeholder Clerk/Convex env vars prevent transitive import failures
- SUMMARY.md documenting 3 tasks, 3 commits, all acceptance criteria met
- 20-case golden set, vitest-evals runner with Factuality + citation scorers
- CI workflow with extraction path filter and RUN_EVALS gate
- Add ~50 new extraction.* keys (jobCreation, progress, results, export groups)
- Add jobsDialogTitle and jobsDialogDescription at extraction root level
- Add metadata.extractionTitle, extractionDescription, extractionResultsTitle
- Existing ~25 extraction keys preserved unchanged in all locales
- Non-English locales use en-US text as placeholder (per project convention)
…rt queries

- getExtractionResults: per-paper results with nested question answers for results page
- getExtractionResultsForExport: flat denormalized rows for CSV/JSON/XLSX serialization
- Both queries include getCurrentUser auth + job.userId ownership guard
- Both use .take(MAX_EXTRACTION_PAPERS_PER_JOB) and .take(100) for bounded collections
- Export query resolves question text from job.questions via key lookup
…ions

- ExtractionExportData interface matching getExtractionResultsForExport return shape
- generateExtractionCSV with escapeCSVCell for proper field escaping
- generateExtractionJSON with metadata envelope (jobId, status, questionCount)
- generateExtractionXLSXWorkbook with Results + Summary sheets, dynamic import('exceljs')
- exportExtractionToCSV/JSON/XLSX download wrappers via Blob URL pattern
- Self-contained module cloned from lib/screening/export.ts pattern
- 3/3 tasks completed: i18n seeding, Convex queries, export module
- All verifications passed, self-check passed
- StatusBadge with 6-status OKLCH color config and animate-pulse for active states
- PaperResultCard composing ConfidenceBadge, CriticVerdictBadge, EvidenceQuote, InsufficientEvidenceCard, StatusBadge
- Staggered card entrance animation via motion.div with reduced motion support
- Added statusParsing and statusExtracting i18n keys across all 6 locales (Rule 3: blocking dependency)
- RESEARCH.md: mark Open Questions 1-4 as (RESOLVED) with CLI shell-out
  pattern committed for Convex seed invocation; abandon ConvexHttpClient path
- VALIDATION.md: flip status to final + nyquist_compliant:true; replace
  phantom test file references with grep+tsc verify chain matching actual
  plan deliverables; align verify map with Plan 01/02/03 task structure
Plan 01 (Wave 1) — ESLint bootstrap + GAP-03 rule + self-test
Plan 02 (Wave 1) — Mobile polish (44px, view-switcher guard) + reduced-motion
Plan 03 (Wave 2) — i18n key-parity + Convex seed action + Playwright E2E

All 6 blockers from plan-checker iteration 1 resolved:
- Frontmatter split: requirements (REQ-IDs) vs success_criteria_addressed (SC-*)
- ConvexHttpClient removed from E2E spec; execFileAsync is canonical
- FRENCH_DIACRITIC_SAMPLES pre-curated with 8 keys; bounds 8..10 enforced
- Atomic splitMobileToast to mobileViewFallbackToast rename sequence
- head -N pipes removed from automated verify chains
- nyquist_compliant:true reconciled in VALIDATION.md

Checker verified iteration 2: all dimensions PASS. Scope noted: Plan 02 at
17 files (6 locale JSONs + 11 TS/CSS/TSX) is justified by atomic rename.
- Add ReducedMotionProvider client wrapper rendering <MotionConfig reducedMotion="user">
- Mount provider inside NextIntlClientProvider, outside ThemeProvider (D-18)
- Append @media (prefers-reduced-motion: reduce) CSS rule to globals.css (D-19)
- Covers both Motion-driven animations and Tailwind/tw-animate-css transitions
- Closes SC-4 (reduced-motion) foundation; existing useReducedMotion() call
  sites in workbench-shell/paper-result-card/question-builder compose
  correctly with the global MotionConfig (D-21)
…step 1/3)

Adds a new sibling key alongside the existing splitMobileToast so every
locale holds both keys during the rename window, keeping set-parity stable
for Plan 03's i18n key-parity test. French translation contains the
diacritic 'à' to satisfy D-25 sampling. Old splitMobileToast key is
preserved here and removed atomically in step 3/3.
… on mobile (105-02 step 2/3)

- view-switcher: conditionally render only the Table option on mobile
  viewports via useIsMobile() guard; card + split options spread into the
  array only when !isMobile (satisfies annotation preserves ActiveView
  narrowing)
- workbench-shell: broaden the D-06 force-switch effect from
  `activeView === "split"` to `activeView !== "table"`, so both card AND
  split fall back to table on <768px viewports; toast switches from the
  old splitMobileToast key to the new mobileViewFallbackToast key (still
  co-exists with the orphan key, removed in step 3/3)
…05-02 step 3/3)

Completes the atomic rename from `extraction.workbench.splitMobileToast`
to `extraction.workbench.mobileViewFallbackToast`. All 6 locales now hold
only the new key; parity restored for Plan 03's i18n key-parity test.
…sket drawer width (105-02 task 3/3)

Closes D-13, D-15, D-16, D-17 for SC-3:

- workbench-toolbar: responsive stack at <640px (flex-col sm:flex-row);
  search-clear button inflated to 44×44 hit area; export button text
  hidden on mobile via <span className="hidden sm:inline"> (DropdownMenu
  wrapper preserved)
- extraction-basket-drawer: SheetContent full-width on mobile, capped at
  sm:max-w-md; footer CTA inflated to min-h-[44px]
- extraction-counter: root wrapper min-h-[44px] with flex-center for
  touch-target compliance
- add-to-extraction-button: Button min-h-[44px] min-w-[44px]
- selector-page-client: TabsList overflow-x-auto; 5× TabsTrigger each
  min-h-[44px]
- zotero-item-row: checkbox wrapper and State-4 retry button each
  min-h-[44px] min-w-[44px]

All edits are additive className patches — no wrapper/structure changes,
no `size` prop changes (preserves visual icon sizes). Plan 03 adds the
E2E touch-target assertions.
Writes 105-02-SUMMARY.md capturing the 5-commit plan (Task 1 reduced-motion,
Task 2 atomic 3-step i18n rename, Task 3 44px touch-target audit + toolbar
stack + basket drawer width), plus deferred-items.md logging two pre-existing
test failures (DEF-105-01 regex-flag TS1501 from Phase 94; DEF-105-02 view-
store test drift from Phase 103) as out-of-scope per executor scope-boundary
rule.
…ed-syntax rule

- Add eslint.config.mjs at repo root extending next/core-web-vitals + next/typescript
- Scope no-restricted-syntax rule to components/extraction/** and app/extraction/**
  blocking Literal[value=1000] and Literal[value=200] with message pointing to
  MAX_EXTRACTION_PAPERS_PER_JOB / getExtractionLimit (D-04 verbatim)
- Add second, more-specific config object exempting test files (D-03)
- Add "lint": "eslint ." script (D-01 adjusted for Next.js 16 next lint removal)
- Prepend "npm run lint &&" to test:ci so broken config fails fast
- Add eslint@^9.39.4 + eslint-config-next@^16.2.4 to devDependencies
…rule

- Runs ESLint programmatically via new ESLint({cwd}) against fake file paths
- Asserts rule fires on Literal[value=1000] in components/extraction/ globs
- Asserts rule fires on Literal[value=200] in app/extraction/ globs
- Asserts rule exempts test files (.test.tsx) via D-03 second config object
- Asserts rule does not fire outside extraction globs (scope verification)
- Protects against silent removal of the rule or its exception (D-05)
- 105-01-SUMMARY.md: 2 tasks committed, 4 files changed, 7m47s duration
- GAP-03 marked complete in REQUIREMENTS.md traceability
- STATE.md advanced to plan 2/3 (96% phase progress), 3 decisions logged,
  blocker recorded for pre-existing GAP-03 violations in extraction-counter.tsx
  and job-metrics-panel.tsx (to be fixed in Plan 02/03)
- ROADMAP.md plan progress updated for Phase 105
- extraction-counter.tsx: replace literal 1000 fallback with MAX_EXTRACTION_PAPERS_PER_JOB import from convex/lib/queryBounds (legitimate paper-cap fallback routed through single source of truth)
- job-metrics-panel.tsx: replace ms/1000 division with MS_PER_SECOND import from new lib/time-units module (false positive -- unit conversion, not paper cap)
- lib/time-units.ts: new shared module for time-unit constants (MS_PER_SECOND, MS_PER_MINUTE, etc.) so extraction UI can import named conversion factors instead of hosting the forbidden literal

Unblocks test:ci lint step for Phase 105 Plan 03.
…r orphans)

- New tests/i18n/v7-key-parity.test.ts: flatten all 6 locale JSONs, assert set equality vs en-US, assert French diacritic presence in 8 curated v7.0 sample paths with bounds [8, 10] (D-23 through D-26).
- Remove orphaned reportBuilder.showingRange and reportBuilder.filteredFrom from en-GB.json: they had no en-US/fr/hi/ja/zh counterpart and were unused in source code (verified via grep across *.tsx/*.ts — all showingRange usages resolve to libraryPage.*, searchFilters.*, or pagination.* namespaces). Removing lets all 6 locales achieve exactly 1540 keys of parity.
- All 8 French samples verified diacritic-bearing in fr.json at commit time.
…lit per Node/V8 runtime rule)

- New convex/extraction/testing.ts ("use node"): `seedCompletedJob` internalAction with optional `title` arg defaulting to `"E2E seed <timestamp>"`. Triple-condition `assertDevEnvironment()` guard (CONVEX_CLOUD_URL localhost OR NODE_ENV=development OR ALLOW_TEST_SEEDING=true).
- New convex/extraction/testingMutations.ts (V8 runtime): `insertSeededJob` internalMutation. REQUIRES `E2E_CLERK_USER_EMAIL` — no "first user in table" fallback. Looks up user via `by_email` index. Inserts extractionJobs (no title field in schema — arg kept for forward-compat), paperCount extractionPapers (doi undefined for even/populated for odd), questionCount extractionQuestions, paperCount*questionCount extractionResults with flat evidence fields and parsingSource: "abstract_only".
- Runtime split required by Convex: `"use node"` modules cannot export mutations (caught by codegen). Rule 3 (blocking issue) — documented in both files.
- Schema-reality adjustments vs plan sketch: extractionJobs has no `title` field, tier union is `"auto"|"cheap"|"accurate"`, status is `"pending"|"processing"|"completed"|"cancelled"|"failed"`, extractionResults uses `questionId` (not `questionKey`), `confidence` is literal `"high"|"medium"|"low"` (not number), evidence is flat fields, and `parsingSource` validator allows `"pmc"|"arxiv"|"unpdf"|"gemini"|"abstract_only"` (plan's `"api"` would have failed validator).
- Verified: `npx convex codegen` succeeds (api.d.ts regenerated with `extraction/testing` + `extraction/testingMutations`); `npx tsc --noEmit` shows only pre-existing DEF-105-01 error (unrelated).
…fixtures + test:ci wiring

- New e2e/helpers/sign-in.ts: `signIn(page)` + `getTestUserEmail()` extracted verbatim from e2e/auth.spec.ts (DRY — shared between auth.spec.ts and new workbench spec).
- Refactor e2e/auth.spec.ts: remove inline helper definitions, import from ./helpers/sign-in; keep @clerk/testing/playwright for clerk.signOut. All 4 existing tests unchanged.
- New e2e/fixtures/zotero-collections.json (3 collections) + e2e/fixtures/zotero-items.json (6 items, 2 without DOI): realistic Zotero API v3 shape for page.route() mocking.
- New e2e/extraction-workbench.spec.ts: `test.describe("v7.0 extraction workbench end-to-end")` with 3 sequential tests sharing seededJobId via beforeAll: (1) stage papers across 5 tabs, (2) seed job + navigate Table/Card/Split + open evidence drawer + reduced-motion <150ms assertion (W7 threshold), (3) export CSV/JSON/XLSX and assert suggestedFilename + byte size >0.
- Seed invocation uses execFileAsync("npx", ["convex", "run", "extraction/testing:seedCompletedJob", ...]) CLI shell-out — zero direct ConvexHttpClient / api / internal imports (keeps Playwright decoupled from Convex codegen per D-06).
- Zotero API mocks use page.route("**/api.zotero.org/**/collections*") and "/items*" with fixture JSON bodies — zero real network traffic to zotero.org.
- package.json: add "test:e2e:workbench" script + extend "test:ci" chain with `&& npm run test:e2e:workbench` after `test:e2e:auth` (Plan 01 added auth; Plan 03 adds workbench).
- Lint cleanup: drop unused `title` destructure param in testingMutations.ts handler (keeps arg in the signature validator, just not destructured in the body).
SUMMARY.md for Plan 03 closing Phase 105 Wave 2:

- Task 1 (a744b80): i18n 6-locale key parity test + en-GB drift cleanup
- Task 2 (5257457): Convex seed action with Node/V8 runtime split
- Task 3 (d7ff57f): full v7.0 workbench E2E spec + helpers + fixtures + test:ci wiring

4 auto-fixed deviations (1 Rule 3 blocking runtime split, 2 Rule 1 schema/lint bugs,
1 Rule 2 missing-critical en-GB drift cleanup). No scope creep.

SC-2/SC-4/SC-5 infrastructure complete; Phase 105 Wave 2 ready for orchestrator merge.
Archive v7.0 Extraction Workbench (8 phases, 23 plans, 339 files
+47K/-3K LOC) to milestones/ with ROADMAP, REQUIREMENTS, and audit
record. Collapse v7.0 section in ROADMAP.md. Update PROJECT.md
with Current State + Next Milestone Goals. Append v7.0 entry to
MILESTONES.md + RETROSPECTIVE.md with known gaps and lessons.
STATE.md marked shipped and deferred items recorded.

35/42 requirements satisfied; 1 unsatisfied (WB-07), 6 partial.
Closes v6.0 UI-01, EXTR-01, PARSE-07, CRASH-02.
Archived to .planning/milestones/v7.0-REQUIREMENTS.md. Fresh REQUIREMENTS.md will be created for v7.1 via /gsd-new-milestone.
Introduced a comprehensive roadmap for the v7.0 Extraction Workbench, detailing milestones and phases from v1.0 to v7.0, including completed tasks and in-progress phases. Added pattern maps for phases 99 to 104, covering the selection basket core, Zotero revival, entry points & counter UX, and workbench views & selector page. Updated extraction list client to utilize the new Extraction Command Center component for improved functionality and user experience.
@sickerine sickerine closed this Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant